#!/bin/bash
# /usr/local/c2csvc/global_conf/ServiceConfig.xml modification tool by cmlchen
# 
# Changelog
# + 2013-09-19    Add Person field to group configure item

conffile="/usr/local/c2csvc/global_conf/ServiceConfig.xml"
cctool="/usr/local/c2cconfig/tools/conf_view_all"
xmlchanged=0
result=0
ExistName=""
ignoresvc=" "

# DeleteGroup function is to delete the command from the configure file
# Usage: DeleteGroup Name
function DeleteGroup()
{
  item="<Group Name=\"$1\".+?/>\s*"
  perl -i -pe "s!$item!!ig" "$conffile"
  xmlchanged=1
  return 0
}

# Check if the CmdId's existing group name differ from the given
# Usage: CheckGroupCmdId Name CmdId
function CheckGroupCmdId()
{
  local ExistPattern="<Group.+Name=\"(\w+)\".+ID=\"$2\""
  local NameAttrub=`grep -Poi "$ExistPattern" "$conffile" | grep -Poi "Name=\"\w+\""`
  
  for NameItem in $NameAttrub
  do
    ExistName=${NameItem:6:${#NameItem}-7}
    
    if [ "`echo $ExistName | tr [:upper:] [:lower:]`" != "`echo $1 | tr [:upper:] [:lower:]`" ]
    then 
      return 1
    fi
  done
  
  ExistName=""
  return 0
}

# ExistsGroup function is to determine if the group exists
# Usage: ExistGroup Name
function ExistGroup()
{
  item="<Group Name=\"$1\".+?/>"
  count=`grep -c -P -i "$item" "$conffile"`
  if [ $count -ge 1 ]
  then 
    return 0
  else
    return 1
  fi
}

# AddOrReplaceGroup function is to add or replace a command to the configure file
# Usage: AddOrReplaceGroup Name CmdId FrontMsgQKey BackMsgQKey Size [LogModule [Person]] 
function AddOrReplaceGroup()
{
  # Set the default value of size
  if [ $5 -le 0 ]
  then
    $5=1
  fi

  # Check if the name differ from previous configure
  if ! CheckGroupCmdId $1 $2
  then
    echo "[Warining]CmdId $2 has already configured a different group name \"$ExistName\". Skipped!"
    ignoresvc="$ignoresvc$1 "
    return 0
  fi

  # If the group exists, then delete it
  if ExistGroup $1
  then
    DeleteGroup $1
  fi

  # Add the group info
  item="<Group Name=\"$1\" ID=\"$2\" FrontMsgQKey=\"$3\" BackMsgQKey=\"$4\" Size=\"$5\" LogModule=\"$6\" Person=\"$7\"/>"
  perl -i -pe "s!</ServiceGroupRoot>!  $item\n</ServiceGroupRoot>!ig" "$conffile"
  xmlchanged=1

  return 0
}

# AddLocalGroup function is to replace the TCP remote group to local group. If the TCP configure doesn't exist, add new group
# Usage: AddLocalGroup Name CmdId FrontMsgQKey BackMsgQKey Size [LogModule [Person]] 
function AddLocalGroup()
{
  # Set the default value of size
  if [ $5 -le 0 ]
  then
    $5=1
  fi
  
  # Check if the name differ from previous configure
  if ! CheckGroupCmdId $1 $2
  then
    echo "[Warining]CmdId $2 has already configured a different group name \"$ExistName\". Skipped!"
    ignoresvc="$ignoresvc$1 "
    return 0
  fi

  # Extract the existing group information
  local pattern="<Group Name=\"$1\" ID=\"([0-9a-fx]+)\" FrontMsgQKey=\"(\w+)\".+?/>"
  local olditem=`grep -P -o -i "$pattern" "$conffile"`
  local newitem="<Group Name=\"$1\" ID=\"$2\" FrontMsgQKey=\"$3\" BackMsgQKey=\"$4\" Size=\"$5\" LogModule=\"$6\" Person=\"$7\"/>"
  
  if [ -z "$olditem" ]   # NOT FOUND
  then
    # Add the group info
    perl -i -pe "s!</ServiceGroupRoot>!  $newitem\n</ServiceGroupRoot>!ig" "$conffile"
    xmlchanged=1
  else
    local fmsgq=`echo "$olditem" | sed -r -e "s!$pattern!\2!i"`
    
    if [ $fmsgq == "TCP" ]     # The group is the remote sevice
    then
      perl -i -pe "s!$olditem!$newitem!ig" "$conffile"
      xmlchanged=1
    else
      echo "[HINT]Non-TCP configure of $1 has already existed. Skipped!"
    fi
  fi
}

# AddGroupIfNotExist function is to add command if the command doesn't exist. 
# Usage: AddGroupIfNotExist Name CmdId FrontMsgQKey BackMsgQKey Size [LogModule [Person]] 
function AddGroupIfNotExist()
{
  # Set the default value of size
  if [ $5 -le 0 ]
  then
    $5=1
  fi

  # Check if the name differ from previous configure
  if ! CheckGroupCmdId $1 $2
  then
    echo "[Warining]CmdId $2 has already configured a different group name \"$ExistName\". Skipped!"
    ignoresvc="$ignoresvc$1 "
    return 0
  fi

  # If the group doesn't exist, then add the configure
  if ! ExistGroup $1
  then
    # Add the group info
    item="<Group Name=\"$1\" ID=\"$2\" FrontMsgQKey=\"$3\" BackMsgQKey=\"$4\" Size=\"$5\" LogModule=\"$6\" Person=\"$7\"/>"
    perl -i -pe "s!</ServiceGroupRoot>!  $item\n</ServiceGroupRoot>!ig" "$conffile"
    xmlchanged=1
  else
    echo "[HINT]The configure of service $1 has already existed, skipped."
  fi

  return 0
}

# Format the content of the local service configuration file
function FormatXML()
{
  if [ $xmlchanged -ne 0 ]
  then
    perl -i -pe "s!\s*<Group !  <Group !ig" "$conffile"
    perl -i -pe "s!\s*</ServiceGroupRoot>!</ServiceGroupRoot>!ig" "$conffile"
    sed "/^\s*$/d" "$conffile" > "$conffile.tmp"
    mv -f "$conffile.tmp" "$conffile"
    chown appadmin:users "$conffile"
  else
    echo "[HINT]The configure file remains no change."
  fi
}

# Print the address from config center
# Usage: PrintCCAddress cmdid/svcname {cmd|svc}
function PrintCCAddress()
{
  local pattern='\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b(:\w{1,5})?'
  local ipaddrs=`$cctool $1 $2 | grep -Po "$pattern" | sort | uniq`
  if [ "$ipaddrs" == "0.0.0.0:0" ]
  then
    echo "$ipaddrs (INVALID)"
    result=-1
  else
    echo $ipaddrs
  fi
}


# Check the local config and print the cmdid
# Usage: CheckLocal Name
function CheckLocal()
{
  echo -n "Checking local $1..."
  local pattern="<Group Name=\"$1\".+?ID=\"(0x[0-9a-f]+)\".+?>"
  local cmdid=`grep -P -o -i "$pattern" "$conffile"| sed -r -e "s/$pattern/\1/i"`
  if [ -z $cmdid ]
  then 
    # Test if the svcname is in the ignore list
    if [ -z "`echo \"$ignoresvc\" | grep -ow \" $1 \"`" ]
    then
      echo "NOT FOUND"
      result=-1    
    else
      echo "Skipped due to pervious skipping configure"
    fi
  else
    echo -n "$cmdid "
    PrintCCAddress $cmdid cmd
  fi
}

# Check the configure centre ip address
# Usage: CheckRemoteService svcname
function CheckRemoteService()
{
  echo -n "Checking remote service from config center[$1].."
  PrintCCAddress $1 svc
}

# Check the running status and the file information
# Usage: CheckService module_name
function CheckService()
{
  echo -n "Checking service $1..."
  local curpath=`pwd`
  cd /usr/local/c2csvc/
  local svcname=`echo $1 | tr '[A-Z]' '[a-z]'`
  local srvstatus=`./svc.sh show $svcname`
  local srvcount=`echo -e "$srvstatus"|wc -l`
  if [ -z "$srvstatus" ]
  then
    echo "NO SERVICE FOUND"
    ls -lrt "/usr/local/c2csvc/so/$svcname.so"
    result=-1
  else
    echo "found $srvcount process running"
    ls -lrt "/usr/local/c2csvc/so/$svcname.so"
    echo -e "$srvstatus"
  fi
  cd "$curpath"
}

# Check DB privilege
# Usage: CheckDBAuth database host port username password
function CheckDBAuth()
{
  echo -n "Checking DB privilege $4@$2:$1..."
  output=`mysql "$1" -h"$2" -P"$3" -u"$4" -p"$5" -N -e 'show grants;' 2>&1`
  retcode=$?
  lnumber=`echo "$output" | wc -l`
  if [ $retcode -eq 0 ]
  then
    echo "Succeed! Found $lnumber record(s)"
  else
    echo "FAILED! Please ignore when runing on test environments."
  fi
  echo "$output"
}

AddLocalGroup ao_crmauth 0xbb1f 766448 766449 10
AddGroupIfNotExist DAO_CRMREGISTER 0xbc15 TCP 0 1
AddGroupIfNotExist ao_tmsuser 0xb000 TCP 0 1
AddGroupIfNotExist AO_EMPLOYEE_WRITE 0xf191 TCP 0 1
AddGroupIfNotExist AO_EMPLOYEE_R 0xf192 TCP 0 1
FormatXML

#( su - appadmin -c "cd /usr/local/c2csvc/ && ./svc.sh restart netio >/dev/null 2>&1" )
#( su - appadmin -c "cd /usr/local/c2csvc/ && ./svc.sh restart back_netio >/dev/null 2>&1" )
#( su - appadmin -c "cd /usr/local/c2csvc/ && ./svc.sh restart ao_crmauth >/dev/null 2>&1" )

#echo "Wait for 5 seconds to verify the installation result"
#sleep 5

CheckLocal ao_crmauth
CheckLocal DAO_CRMREGISTER
CheckLocal ao_tmsuser
CheckLocal AO_EMPLOYEE_WRITE
CheckLocal AO_EMPLOYEE_R
CheckService ao_crmauth
exit $result
